package demo1;

import java.util.HashMap;
import java.util.Map;

public class LeetCode904 {
    public int totalFruit1(int[] fruits) {
        int ret = 0, n = fruits.length;
        Map<Integer, Integer> hash = new HashMap<>();
        for(int left = 0, right = 0; right < n; right++) {
            int in = fruits[right];  //进窗口
            hash.put(in, hash.getOrDefault(in, 0) + 1);
            while(hash.size() > 2) {
                int out = fruits[left];  //出窗口
                hash.put(out, hash.get(out) - 1);
                if(hash.get(out) == 0) hash.remove(out);
                left++;
            }
            ret = Math.max(ret, right - left + 1);
        }
        return ret;
    }

    public int totalFruit2(int[] fruits) {
        int n = fruits.length, ret = 0;
        int[] hash = new int[n + 1];
        for(int left = 0, right = 0, kinds = 0; right < n; right++) {
            int in = fruits[right];
            if(hash[in] == 0) kinds++;
            hash[in]++;
            while(kinds > 2) {
                int out = fruits[left];
                hash[out]--;
                if(hash[out] == 0) kinds--;
                left++;
            }
            ret = Math.max(ret , right - left + 1);
        }
        return ret;
    }
}
